import * as fgui from "fairygui-cc";
import AbstractUIWindow from "../../window/AbstractUIWindow";
import UICore from "../../../../Core/Res/UICore";
import { Plane } from "./component/Plane";
import { Grid } from "./component/Grid";
import { GameModels } from "../../socket/GameModels";
import { ModelGameRobot } from "../../model/ModelGameRobot";
import { ViewManager } from "../../base/ViewManager";
import { LocalUtil } from "../../../../Core/Utils/LocalUtil";
import EventMgr from "../../../../Core/Event/EventMgr";
import ProtoBufManager from "../../../proto/ProtoBufManager";
import { common, game } from "../../../proto/protoCmd";
import TimerMgr from "../../../../Core/Timer/TimerMgr";
import ModuleWindow from "../../window/ModuleWindow";
import WindowObject from "../../window/WindowObject";
import SdkTool from "../../../../Core/Sdk/SdkTool";
import AudioManager from "../../../../Core/Audio/AudioManager";
import { SkillItemRender } from "./component/SkillItemRender";
import { tween } from "cc";
import { ItemVO } from "../../vo/ItemVO";
import Log from "../../../../Core/Log/Log";

export class PlayView extends AbstractUIWindow {
    private isRoom: boolean = false;//是否为自定义房间
    private isoverlap: boolean = false;//飞机是否重叠
    private btnExit: fgui.GButton;
    private tip: fgui.GTextField;
    private tip1: fgui.GTextField;
    private mpboard: fgui.GComponent;
    private mpboardplane1: Plane;
    private mpboardplane2: Plane;
    private mpboardplane3: Plane;
    private mpboardplaneList: Array<Plane>;
    private otherboard: fgui.GComponent;
    private ctrl_state: fgui.Controller;
    private otherboardplane1: Plane;
    private otherboardplane2: Plane;
    private otherboardplane3: Plane;
    private otherboardplaneList: Array<Plane>;
    private clicklist: fgui.GList;
    private ok: fgui.GButton;
    private random: fgui.GButton;
    private pos_dict: object = {};//坐标映射
    private roundtxt: fgui.GTextField;
    private invite: fgui.GButton;
    private over: fgui.GComponent;
    private ctrl_state1: fgui.Controller;
    private again: fgui.GButton;
    private exitroom: fgui.GButton;
    private myboardXY: number[] = [];
    private myplayerAtt: Grid[] = [];
    private touchMask: fgui.GLoader;
    private mode: fgui.GButton;
    private ctrl_modestate: fgui.Controller;
    private myplanestr: string;
    private skillList: fgui.GList;
    private useItem: number = 0;
    private useSkill: boolean = false;
    private useSkillCount: number = 0;
    private ctrl_myhudun: fgui.Controller;
    private ctrl_otherhudun: fgui.Controller;
    private AtkMask: fgui.GComponent;
    private AtkMaskselect: fgui.GImage;

    private topbar: fgui.GComponent;
    private wofang: fgui.GComponent;
    private difang: fgui.GComponent;

    hedan: any;
    zhuizong: any;
    private otherUserItem: number;
    // private AtkMaskatk: fgui.GButton;
    // private AtkMaskindex: fgui.GButton;
    protected getResList(): Array<string> {
        return [`Plane`];
    }
    protected onInit(): void {
        this._view = UICore.createObject("Plane", "PlayView").asCom;
    }
    protected onShow(isRoom: boolean = false): void {
        GameModels.game.Round = 0;
        EventMgr.on(`planeTest`, this.planeTest, this);
        EventMgr.on(`closeRobot`, this.close, this);
        EventMgr.on(`event_SyncGameEnd`, this.onSyncGameEnd, this)
        EventMgr.on(`event_SyncGameMateSuccess`, this.onSyncGameMateSuccess, this);
        EventMgr.on(`event_RespRecordData`, this.onRespRecordData, this);
        // EventMgr.on(`event_RespCreateRoom`, this.onSyncGameMateSuccess, this);
        EventMgr.on(`event_SyncGameAck`, this.onSyncGameAck, this);
        EventMgr.on(`event_SyncGameRoundStart`, this.onSyncGameRoundStart, this);
        EventMgr.on(`event_SyncUserEnterRoom`, this.onSyncUserEnterRoom, this);
        EventMgr.on(`event_SyncUserExitRoom`, this.onSyncUserExitRoom, this);
        EventMgr.on(`event_RespFinishLoadGame`, this.onRespFinishLoadGame, this);
        this.ctrl_myhudun = this.mpboard.getController(`ctrl_hudun`);
        this.ctrl_otherhudun = this.otherboard.getController(`ctrl_hudun`);
        this.AtkMaskselect = this.AtkMask.getChild(`select`) as fgui.GImage;
        this.hedan = this.AtkMask.getChild(`ceshi`);
        this.zhuizong = this.AtkMask.getChild(`ceshi2`);
        this.ctrl_state1 = this.over.getController(`ctrl_state1`);
        this.again = this.over.getChild(`again`) as fgui.GButton;
        this.exitroom = this.over.getChild(`exitroom`) as fgui.GButton;
        this.exitroom.onClick(this.clickExitRoom, this);
        this.again.onClick(this.clickagain, this);
        this.invite.onClick(this.clickinvite, this);
        this.touchMask.onClick(this.clicktouchMask, this);
        this.isRoom = isRoom;
        this.over.visible = false;
        this.ctrl_state.onChanged(this.changestate, this);
        this.invite.visible = false;
        if (this.isRoom && GameModels.lobby.roomPlayerState == 1) {
            this.invite.visible = true;
        }

        this.mode = this.otherboard.getChild(`mode`) as fgui.GButton;
        this.ctrl_modestate = this.otherboard.getController(`ctrl_state`);
        this.ctrl_modestate.onChanged(this.changemode, this);
        // this.mpboard.onClick(this.click_mpboard, this);
        this.myboardXY = [this.mpboard.x, this.mpboard.y, this.mpboard.width, this.mpboard.height];
        // this.otherboard.onClick(this.click_otherboard, this);
        this.btnExit.onClick(this.click_btnExit, this);
        this.otherboardplane1 = this.otherboard.getChild('plane').asCom.getChild("plane1") as Plane;
        this.otherboardplane2 = this.otherboard.getChild('plane').asCom.getChild("plane2") as Plane;
        this.otherboardplane3 = this.otherboard.getChild('plane').asCom.getChild("plane3") as Plane;
        this.otherboardplaneList = [this.otherboardplane1, this.otherboardplane2, this.otherboardplane3];
        this.clicklist = this.otherboard.getChild(`clicklist`) as fgui.GList;
        this.clicklist.on(fgui.Event.CLICK_ITEM, this.onRender, this);
        this.resetOther();

        this.tip = this.topbar.getChild("tip") as fgui.GTextField
        this.tip1 = this.topbar.getChild("tip1") as fgui.GTextField
        this.wofang = this.topbar.getChild("wofang") as fgui.GComponent
        this.difang = this.topbar.getChild("difang") as fgui.GComponent
        this.difang.visible = false

        this.tip.text = `准备阶段`;
        this.roundtxt.text = `准备中`;
        this.mpboardplane1 = this.mpboard.getChild('plane').asCom.getChild("plane1") as Plane;
        this.mpboardplane2 = this.mpboard.getChild('plane').asCom.getChild("plane2") as Plane;
        this.mpboardplane3 = this.mpboard.getChild('plane').asCom.getChild("plane3") as Plane;
        this.mpboardplaneList = [this.mpboardplane1, this.mpboardplane2, this.mpboardplane3];
        this.ok = this.mpboard.getChild(`ok`) as fgui.GButton;
        this.ok.onClick(this.clickOK, this);
        this.random = this.mpboard.getChild(`random`) as fgui.GButton;
        this.random.onClick(this.randommpboard, this);
        this.resetMy();
        this.tip1.text = ``;
        TimerMgr.ins.add(1000, -1, this.timedown, this);
        (this.wofang.getChild(`headUrl`) as fgui.GLoader).url = GameModels.info.playerInfo.headUrl;
        (this.wofang.getChild(`nameTxt`) as fgui.GTextField).text = GameModels.info.playerInfo.userName;
        // (this.mpboard.getChild(`fightCount`) as fgui.GTextField).text = `战斗场次:${GameModels.info.playerInfo.fightCount}`;
        // (this.mpboard.getChild(`winRate`) as fgui.GTextField).text = `胜率:${GameModels.info.playerInfo.winRate}%`;
        // (this.mpboard.getChild(`eliminateCount`) as fgui.GTextField).text = `击落敌机:${GameModels.info.playerInfo.eliminateCount}`;
        this.onRespRecordData();
        GameModels.lobby.send_ReqRecordData();
        this.setOtherInfo();
        this.skillList.itemRenderer = this.onskillList.bind(this);
        this.skillList.on(fgui.Event.CLICK_ITEM, this.clickSkillList, this);
        this.skillList.numItems = GameModels.bag.skillItem.length;
    }
    private onskillList(index: number, item: SkillItemRender): void {
        const vo: ItemVO = GameModels.bag.skillItem[index];
        item.setDate(vo, vo.count);
    }
    private setOtherInfo(): void {
        if (!GameModels.lobby.OtherPlayer) {
            (this.difang.getChild(`headUrl`) as fgui.GLoader).url = ``;
            (this.difang.getChild(`nameTxt`) as fgui.GTextField).text = ``;
            (this.difang.getChild(`fightCount`) as fgui.GTextField).text = ``;
            (this.difang.getChild(`winRate`) as fgui.GTextField).text = ``;
            (this.difang.getChild(`eliminateCount`) as fgui.GTextField).text = ``;
            return;
        }
        Log.ins.log(1, `对手头像：` + GameModels.lobby.OtherPlayer.headUrl);
        (this.difang.getChild(`headUrl`) as fgui.GLoader).url = GameModels.lobby.OtherPlayer.headUrl;
        (this.difang.getChild(`nameTxt`) as fgui.GTextField).text = GameModels.lobby.OtherPlayer.userName;
        (this.difang.getChild(`fightCount`) as fgui.GTextField).text = `战斗场次:${GameModels.lobby.OtherPlayer.fightCount}`;
        (this.difang.getChild(`winRate`) as fgui.GTextField).text = `胜率:${GameModels.lobby.OtherPlayer.winRate}%`;
        (this.difang.getChild(`eliminateCount`) as fgui.GTextField).text = `击落敌机:${GameModels.lobby.OtherPlayer.eliminateCount}`;
    }
    private onRespRecordData(): void {
        (this.wofang.getChild(`fightCount`) as fgui.GTextField).text = `战斗场次:${GameModels.info.playerInfo.fightCount}`;
        (this.wofang.getChild(`winRate`) as fgui.GTextField).text = `胜率:${GameModels.info.playerInfo.winRate}%`;
        (this.wofang.getChild(`eliminateCount`) as fgui.GTextField).text = `击落敌机:${GameModels.info.playerInfo.eliminateCount}`;
    }
    private timedown(): void {
        if (GameModels.game.AckTime > 0) {
            this.tip1.text = `(${GameModels.game.AckTime--})`;
        } else {
            this.tip1.text = ``;
        }
    }
    private clickagain(): void {
        this.over.visible = false;
        this.ctrl_state.selectedIndex = 0;
        this.resetMy();
        for (let i of this.myplayerAtt) {
            i.dispose();
        }
        this.myplayerAtt = [];
        this.resetOther();
        this.tip.text = `准备阶段`;
        this.roundtxt.text = `准备中`;
        this.mpboardplaneList[0].addClick();
        this.mpboardplaneList[1].addClick();
        this.mpboardplaneList[2].addClick();
        this.ok.visible = true;
        this.random.visible = true;

    }
    private onSyncUserEnterRoom(player: common.IGamePlayerInfo): void {
        ViewManager.ins.showtips(`玩家${player.NickName}加入房间,游戏准备开始`);
        // this.roomInfo.visible = false;
        this.invite.visible = false;
        this.setOtherInfo();
    }
    private onSyncUserExitRoom(): void {
        ViewManager.ins.showtips(`对方退出房间`);
        this.invite.visible = true;
        this.setOtherInfo();
    }
    private onRespFinishLoadGame(): void {
        this.roundtxt.text = `已准备`;
    }
    private onSyncGameRoundStart(UseItemIds?: number[]): void {
        this.roundtxt.text = `第${GameModels.game.Round}回合`;
        this.hideAtkMask();
        this.tip1.text = `(${GameModels.game.AckTime--})`;
        TimerMgr.ins.remove(this.updateroundover, this);
        if (UseItemIds && UseItemIds[0] === 1005) {
            this.otherUserItem = 1005;
        }
        if (GameModels.game.AckUid == GameModels.info.playerInfo.UserId) {
            this.tip.text = `我的回合`;
            if (UseItemIds && UseItemIds[0] == 1004) {
                ViewManager.ins.showtips(`对方干扰弹生效,无法攻击`);
                AudioManager.ins.playShot(`music/v7`);
                TimerMgr.ins.add(500, 1, this.updateroundover, this);
                return;
            }
            this.useSkill = false;
            if (this.ctrl_modestate.selectedIndex == 1) {
                ViewManager.ins.showtips(`请切换到作战模式进行攻击`);
            } else {
                ViewManager.ins.showtips(`轮到我方攻击`);
            }
            this.ctrl_state.selectedIndex = 1;
            // this.clicklist.touchable = true;
        } else {
            this.tip.text = `对方回合`;
            ViewManager.ins.showtips(`轮到对方攻击`);
            // this.ctrl_state.selectedIndex = 0;
            // this.clicklist.touchable = false;
        }
    }
    private onSyncGameAck(uid: number, pos: game.IAttackSnapshot[], useitem?: number): void {
        const usehundun = this.otherUserItem === 1005;
        this.otherUserItem = 0;
        if (uid === GameModels.info.playerInfo.UserId) {
            if (usehundun) {
                this.ctrl_otherhudun.selectedIndex = 1;
            }
            if (!useitem) {
                if (usehundun) {
                    ViewManager.ins.showtips(`对方护盾生效,攻击无效`);
                    AudioManager.ins.playShot(`music/v5`);
                    TimerMgr.ins.add(500, 1, () => {
                        this.ctrl_otherhudun.selectedIndex = 0;
                    }, this);
                    TimerMgr.ins.add(1000, 1, this.updateroundover, this);
                    return;
                }
                const xx = pos[0].Pos.X | 0;
                const yy = pos[0].Pos.Y | 0;
                const PType = pos[0].PType | 0;
                const grid = (this.clicklist.getChildAt(this.pos_dict[`${xx}-${yy}`]) as Grid);
                switch (PType) {
                    case ProtoBufManager.ins.game.EPosType.None:
                        ViewManager.ins.showtips(`未命中敌方飞机`);
                        grid.setCtrlState(3);
                        break;
                    case ProtoBufManager.ins.game.EPosType.Body:
                        ViewManager.ins.showtips(`命中敌方飞机`);
                        SdkTool.ins.playShock();
                        AudioManager.ins.playShot(`music/v1`);
                        grid.setCtrlState(4);
                        break;
                    case ProtoBufManager.ins.game.EPosType.Head:
                        ViewManager.ins.showtips(`击毁敌方飞机`);
                        SdkTool.ins.playShock();
                        AudioManager.ins.playShot(`music/v2`);
                        grid.setCtrlState(5);
                        break;
                }
                this.tip1.text = `(${GameModels.game.AckTime--})`;
                TimerMgr.ins.add(1000, 1, this.updateroundover, this);
            } else {
                const fun = () => {
                    for (let i of pos) {
                        const xx = i.Pos.X | 0;
                        const yy = i.Pos.Y | 0;
                        const PType = i.PType | 0;
                        const grid = (this.clicklist.getChildAt(this.pos_dict[`${xx}-${yy}`]) as Grid);
                        switch (PType) {
                            case ProtoBufManager.ins.game.EPosType.None:
                                grid.setCtrlState(3);
                                break;
                            case ProtoBufManager.ins.game.EPosType.Body:
                                grid.setCtrlState(4);
                                break;
                            case ProtoBufManager.ins.game.EPosType.Head:
                                grid.setCtrlState(5);
                                break;
                        }
                    }
                }
                const xx = pos[0].Pos.X | 0;
                const yy = pos[0].Pos.Y | 0;
                // const grid = (this.clicklist.getChildAt(this.pos_dict[`${pos[0].Pos.X}-${pos[0].Pos.Y}`]) as Grid);
                this.AtkMaskselect.x = (xx * 70) + this.myboardXY[0];
                this.AtkMaskselect.y = (yy * 70) + this.myboardXY[1];
                this.AtkMask.visible = true;
                if (useitem === 1002) {
                    this.zhuizong.visible = true;
                    this.zhuizong.x = this.AtkMaskselect.x + 35;
                    this.zhuizong.y = 1334;
                    AudioManager.ins.playShot(`music/v6`);
                    tween(this.zhuizong).to(2.0, { y: this.AtkMaskselect.y + 35 }).delay(0.1).call(() => {
                        this.hideAtkMask();
                        SdkTool.ins.playShock();
                        if (usehundun) {
                            this.ctrl_otherhudun.selectedIndex = 0;
                            ViewManager.ins.showtips(`对方护盾生效,攻击无效`);
                            AudioManager.ins.playShot(`music/v5`);
                            return;
                        }
                        const PType = pos[0].PType | 0;
                        switch (PType) {
                            case ProtoBufManager.ins.game.EPosType.None:
                                break;
                            case ProtoBufManager.ins.game.EPosType.Body:
                                AudioManager.ins.playShot(`music/v1`);
                                break;
                            case ProtoBufManager.ins.game.EPosType.Head:
                                AudioManager.ins.playShot(`music/v2`);
                                break;
                        }
                        fun();
                    }, this).start();
                    TimerMgr.ins.add(3000, 1, this.updateroundover, this);
                } else if (useitem === 1003) {
                    this.hedan.x = this.AtkMaskselect.x + 35;
                    this.hedan.y = 0;
                    this.hedan.visible = true;
                    AudioManager.ins.playShot(`music/v3`);
                    tween(this.hedan).to(8.5, { y: this.AtkMaskselect.y + 70 }).delay(0.1).call(() => {
                        this.hideAtkMask();
                        if (usehundun) {
                            this.ctrl_otherhudun.selectedIndex = 0;
                            ViewManager.ins.showtips(`对方护盾生效,攻击无效`);
                            AudioManager.ins.playShot(`music/v5`);
                            return;
                        }
                        SdkTool.ins.playShock();
                        fun();
                    }, this).start();
                    TimerMgr.ins.add(9000, 1, this.updateroundover, this);
                }
            }

            // GameModels.game.AckTime = 3;
            // this.tip.text = `等待`;

        } else {
            if (!useitem) {
                if (usehundun) {
                    ViewManager.ins.showtips(`护盾生效,对方攻击无效`);
                    this.ctrl_myhudun.selectedIndex = 0;
                    AudioManager.ins.playShot(`music/v5`);
                    return;
                }
                const grid: Grid = UICore.createObject(`Plane`, `Grid`, Grid) as Grid;
                this.myplayerAtt.push(grid);
                this.mpboard.addChild(grid);
                const xx = pos[0].Pos.X | 0;
                const yy = pos[0].Pos.Y | 0;
                const PType = pos[0].PType | 0;
                const posx = ModelGameRobot.mesh()[xx][yy];
                grid.setPosition(posx["x"], posx[`y`]);
                switch (PType) {
                    case ProtoBufManager.ins.game.EPosType.None:
                        grid.setCtrlState(3);
                        break;
                    case ProtoBufManager.ins.game.EPosType.Body:
                        ViewManager.ins.showtips(`命中我方飞机`);
                        SdkTool.ins.playShock();
                        AudioManager.ins.playShot(`music/v1`);
                        grid.setCtrlState(4);
                        break;
                    case ProtoBufManager.ins.game.EPosType.Head:
                        ViewManager.ins.showtips(`击毁我方飞机`);
                        SdkTool.ins.playShock();
                        AudioManager.ins.playShot(`music/v2`);
                        grid.setCtrlState(5);
                        break;
                }
            } else {
                const xx = pos[0].Pos.X | 0;
                const yy = pos[0].Pos.Y | 0;
                // const grid = (this.clicklist.getChildAt(this.pos_dict[`${xx}-${pos[0].Pos.Y}`]) as Grid);
                this.AtkMaskselect.x = (xx * 70) + this.myboardXY[0];
                this.AtkMaskselect.y = (yy * 70) + this.myboardXY[1];
                this.AtkMask.visible = true;
                const fun = () => {
                    for (let i of pos) {
                        const grid: Grid = UICore.createObject(`Plane`, `Grid`, Grid) as Grid;
                        this.myplayerAtt.push(grid);
                        this.mpboard.addChild(grid);
                        const xx = i.Pos.X | 0;
                        const yy = i.Pos.Y | 0;
                        const PType = i.PType | 0;
                        const posx = ModelGameRobot.mesh()[xx][yy];
                        grid.setPosition(posx["x"], posx[`y`]);
                        switch (PType) {
                            case ProtoBufManager.ins.game.EPosType.None:
                                grid.setCtrlState(3);
                                break;
                            case ProtoBufManager.ins.game.EPosType.Body:
                                grid.setCtrlState(4);
                                break;
                            case ProtoBufManager.ins.game.EPosType.Head:
                                grid.setCtrlState(5);
                                break;
                        }
                    }
                }
                this.ctrl_state.selectedIndex = 0;
                if (useitem === 1002) {
                    AudioManager.ins.playShot(`music/v6`);
                    ViewManager.ins.showtips(`追踪导弹来袭！！！`);
                    this.zhuizong.visible = true;
                    this.zhuizong.x = this.AtkMaskselect.x + 35;
                    this.zhuizong.y = 1334;
                    tween(this.zhuizong).to(2.0, { y: this.AtkMaskselect.y + 35 }).delay(0.1).call(() => {
                        this.hideAtkMask();
                        SdkTool.ins.playShock();
                    }, this).start();
                    TimerMgr.ins.add(2000, 1, () => {
                        if (usehundun) {
                            ViewManager.ins.showtips(`护盾生效,对方攻击无效`);
                            this.ctrl_myhudun.selectedIndex = 0;
                            AudioManager.ins.playShot(`music/v5`);
                            return;
                        }
                        const PType = pos[0].PType | 0;
                        switch (PType) {
                            case ProtoBufManager.ins.game.EPosType.None:
                                break;
                            case ProtoBufManager.ins.game.EPosType.Body:
                                AudioManager.ins.playShot(`music/v1`);
                                break;
                            case ProtoBufManager.ins.game.EPosType.Head:
                                AudioManager.ins.playShot(`music/v2`);
                                break;
                        }
                        fun();
                    }, this);

                } else if (useitem === 1003) {
                    ViewManager.ins.showtips(`核弹来袭！！！`);
                    AudioManager.ins.playShot(`music/v3`);
                    this.hedan.x = this.AtkMaskselect.x + 35;
                    this.hedan.y = 0;
                    this.hedan.visible = true;
                    tween(this.hedan).to(8.5, { y: this.AtkMaskselect.y + 70 }).delay(0.1).call(() => {
                        this.hideAtkMask();
                        SdkTool.ins.playShock();
                    }, this).start();
                    TimerMgr.ins.add(8500, 1, () => {
                        if (usehundun) {
                            ViewManager.ins.showtips(`护盾生效,对方攻击无效`);
                            this.ctrl_myhudun.selectedIndex = 0;
                            AudioManager.ins.playShot(`music/v5`);
                            return;
                        }
                        fun();
                    }, this);
                    TimerMgr.ins.add(9000, 1, this.updateroundover, this);
                }
            }
        }
    }
    private updateroundover(): void {
        this.useSkill = true;
        GameModels.game.send_ReqRoundFinish();
    }
    /**匹配成功 */
    private onSyncGameMateSuccess(): void {
        let PanelDate: game.PanelDate = ProtoBufManager.ins.game.PanelDate.create();
        for (let p = 0; p < this.mpboardplaneList.length; p++) {
            const plane = this.mpboardplaneList[p] as Plane;
            let pinfo: game.PlaneInfo = ProtoBufManager.ins.game.PlaneInfo.create();
            pinfo.Eori = plane.state;
            for (let i = 0; i < plane.gridArray.length; i++) {
                const pos: string[] = plane.gridArray[i].split(`-`);
                const coord = ProtoBufManager.ins.game.Coord.create();
                coord.X = Number(pos[0]);
                coord.Y = Number(pos[1]);
                if (i == 0) {
                    pinfo.HeadPos = coord;
                } else {
                    pinfo.PosDate.push(coord);
                }

            }
            PanelDate.Date.push(pinfo);
        }
        this.setOtherInfo();
        GameModels.game.send_ReqFinishLoadGame(PanelDate, `${this.mpboardplaneList[0].clientPos}|${this.mpboardplaneList[1].clientPos}|${this.mpboardplaneList[2].clientPos}`);
        this.ctrl_modestate.selectedIndex = 0;
        ViewManager.ins.removeRanging();
    }
    private startGame(): void {
        this.ok.visible = false;
        this.random.visible = false;
        this.mpboardplaneList[0].removeClick();
        this.mpboardplaneList[1].removeClick();
        this.mpboardplaneList[2].removeClick();
        if (!this.isRoom) {
            GameModels.lobby.send_ReqRandomMateGame();
            ViewManager.ins.showRanging(() => {

            });
        } else {
            this.onSyncGameMateSuccess();
            // if (GameModels.lobby.roomPlayerState == 2) {
            // } else {
            //     // this.roomInfo.visible = true;
            // }
        }

    }
    private resetMy(): void {
        this.myplanestr = LocalUtil.ins.getCookie(`plane1`);
        if (this.myplanestr) {
            this.pullmpboard(this.myplanestr);
        } else {
            this.randommpboard();
        }
    }
    private pullmpboard(str): void {
        if (!str) {
            return;
        }
        const pla = str.split(`|`);
        for (let i = 0; i < pla.length; i++) {
            const pos = pla[i].split(`+`)[0];
            const ratio = pla[i].split(`+`)[1];
            const x = Number(pos.split(`-`)[0])
            const y = Number(pos.split(`-`)[1])
            this.mpboardplaneList[i].x = ModelGameRobot.mesh()[x][y][`x`];
            this.mpboardplaneList[i].y = ModelGameRobot.mesh()[x][y][`y`];
            this.mpboardplaneList[i].setposTarget(this.myboardXY[0], this.myboardXY[1], this.view.x, this.view.y, this.myboardXY[2], this.myboardXY[3]);
            this.mpboardplaneList[i].state = Number(ratio);

            this.otherboardplaneList[i].x = ModelGameRobot.mesh()[x][y][`x`];
            this.otherboardplaneList[i].y = ModelGameRobot.mesh()[x][y][`y`];
            this.otherboardplaneList[i].setposTarget(this.myboardXY[0], this.myboardXY[1], this.view.x, this.view.y, this.myboardXY[2], this.myboardXY[3]);
            this.otherboardplaneList[i].state = Number(ratio);

        }
    }
    private pullotherboard(str): void {
        if (!str) {
            return;
        }
        const pla = str.split(`|`);
        for (let i = 0; i < pla.length; i++) {
            if (!this.otherboardplaneList[i]) {
                continue;
            }
            const pos = pla[i].split(`+`)[0];
            const ratio = pla[i].split(`+`)[1];
            const x = Number(pos.split(`-`)[0]);
            const y = Number(pos.split(`-`)[1]);
            this.otherboardplaneList[i].x = ModelGameRobot.mesh()[x][y][`x`];
            this.otherboardplaneList[i].y = ModelGameRobot.mesh()[x][y][`y`];
            this.otherboardplaneList[i].state = Number(ratio);
        }
    }
    private randommpboard(): void {
        this.myplanestr = ModelGameRobot.randomthreeplane();
        this.pullmpboard(this.myplanestr);
    }
    private clickOK(): void {
        if (this.isoverlap) {
            ViewManager.ins.showtips("不能摆放重叠的飞机");
            return;
        }
        this.startGame();
    }
    private planeTest(): void {
        const result = ModelGameRobot.findDuplicates(this.mpboardplane1.gridArray, this.mpboardplane2.gridArray, this.mpboardplane3.gridArray);
        this.mpboardplane1.overlap(result);
        this.mpboardplane2.overlap(result);
        this.mpboardplane3.overlap(result);
        this.isoverlap = result.length > 0;
    }
    /**初始化敌方棋盘 */
    private resetOther(): void {
        for (let i of this.otherboardplaneList) {
            i.removeClick();
            i.visible = false;
        }
        this.clicklist.numItems = 100;
        this.pos_dict = {}
        let _count = 0;
        // const f = { 0: `A`, 1: `B`, 2: `C`, 3: `D`, 4: `E`, 5: `F`, 6: `G`, 7: `H`, 8: `I`, 9: `J` };
        for (let i = 0; i < ModelGameRobot.mesh().length; i++) {
            for (let j = 0; j < ModelGameRobot.mesh()[0].length; j++) {
                const grid = (this.clicklist.getChildAt(_count++) as Grid);
                grid.title = ``;
                grid.data = `${i}-${j}`;
                this.pos_dict[grid.data] = _count - 1;
                grid.setCtrlState(0);
                grid.setColor();
            }
        }

    }
    private onRender(grid: Grid): void {
        if (this.otherboard.scaleX < 0.9) {
            Log.ins.log(1, `缓动中，不处理点击事件`);
            return;
        }
        if (GameModels.game.Round <= 0) {
            ViewManager.ins.showtips(`游戏未开始`);
            return;
        }
        if (!GameModels.game.AckUid || GameModels.game.AckUid != GameModels.info.playerInfo.UserId) {
            ViewManager.ins.showtips(`不是我的回合，无法攻击`);
            return;
        }
        if (grid.state == 3 || grid.state == 4 || grid.state == 5) {
            Log.ins.log(1, `${grid.title} 已被攻击点位，不处理点击事件`);
            return;
        }

        const str = grid.data as string;
        const coord = ProtoBufManager.ins.game.Coord.create();
        coord.X = Number(str.split(`-`)[0]);
        coord.Y = Number(str.split(`-`)[1]);
        if (this.useSkill && this.useItem === 1003) {
            GameModels.game.send_ReqUseItem(1003, coord);
            return;
        }
        GameModels.game.send_ReqAttack(coord);
        // this.clicklist.touchable = false;
    }
    // private click_mpboard(): void {
    //     if (this.mpboard.scaleX != 1) {
    //         if (this.ok.visible) {
    //             this.mpboardplaneList[0].addClick();
    //             this.mpboardplaneList[1].addClick();
    //             this.mpboardplaneList[2].addClick();
    //         }
    //         this.ctrl_state.selectedIndex = 0;
    //     }
    // }
    // private click_otherboard(): void {
    //     if (this.otherboard.scaleX != 1) {
    //         this.mpboardplaneList[0].removeClick();
    //         this.mpboardplaneList[1].removeClick();
    //         this.mpboardplaneList[2].removeClick();
    //         this.ctrl_state.selectedIndex = 1;
    //     }
    // }
    private click_btnExit(): void {
        ModuleWindow.ins.openWindow(WindowObject.ins.ExitRoomWindow, () => {
            GameModels.game.send_ReqExitGame();
            this.close();
        });

    }
    protected onClose(): void {
        TimerMgr.ins.remove(this.timedown, this);

    }
    private onSyncGameEnd(info: game.SyncGameEnd): void {
        this.hideAtkMask();
        this.over.visible = true;
        this.useSkillCount = 0;
        this.useSkill = false;
        TimerMgr.ins.remove(this.updateroundover, this);
        GameModels.support.send_ReqGetItemBagList();
        // Log.ins.log(1, info.OtherPanel)
        if (info.OtherPanel) {
            let txt = ``;
            for (let i = 0; i < info.OtherPanel.Date.length; i++) {
                const pos: game.IPlaneInfo = info.OtherPanel.Date[i];
                const eori = pos.Eori | 0;
                const zero = ModelGameRobot.zeroPoint(eori);
                const xx = pos.HeadPos.X | 0;
                const yy = pos.HeadPos.Y | 0;
                txt += `${(xx + zero[0])}-${(yy + zero[1])}+${eori}|`;
            }
            // Log.ins.log(1, txt);
            this.pullotherboard(txt);
        }
        for (let i of info.Results) {
            if (GameModels.info.playerInfo.UserId == i.Uid) {
                this.ctrl_state1.selectedIndex = i.Result;
                AudioManager.ins.playShot(`music/${i.Result == 1 ? 'win' : 'lose'}`);
                break;
            }
        }
        this.ctrl_modestate.selectedIndex = 1;
        this.tip.text = `已结束`;

    }
    private hideAtkMask(): void {
        this.AtkMask.visible = false;
        this.hedan.visible = false;
        this.zhuizong.visible = false;
    }
    private clickinvite(): void {
        SdkTool.ins.sdk.shareAppMessage(`我已创建房间，就等你来了！`, `roomid=${GameModels.lobby.RoomId}&nickname=${GameModels.info.playerInfo.NickName}`);
    }
    private clickExitRoom(): void {
        GameModels.game.send_ReqExitGame();
        this.close();
    }
    private clicktouchMask(): void {
        this.ctrl_state.selectedIndex = this.ctrl_state.selectedIndex == 0 ? 1 : 0;
    }

    private changestate(): void {
        this.otherboardplaneList[0].stopDrag();
        this.otherboardplaneList[1].stopDrag();
        this.otherboardplaneList[2].stopDrag();
        for (let i of this.otherboardplaneList) {
            if (i.y < 0) {
                i.x = 0;
                i.y = 0;
            }
        }
        if (this.ctrl_state.selectedIndex == 1) {
            this.otherboard.touchable = true;
            this.mpboard.touchable = false;
            this.wofang.visible = false
            this.difang.visible = true
        } else {
            this.otherboard.touchable = false;
            this.mpboard.touchable = true;
            this.difang.visible = false
            this.wofang.visible = true
        }

    }
    private changemode(): void {
        if (this.ctrl_modestate.selectedIndex == 0) {
            //作战模式
            ViewManager.ins.showtips("已切换作战模式");
            this.clicklist.touchable = true;
            for (let i of this.otherboardplaneList) {
                i.visible = false;
                i.alpha = 1;
                i.removeClick();
            }
            for (let i = 0; i < this.clicklist.numItems; i++) {
                const grid = this.clicklist.getChildAt(i) as Grid;
                if (grid.state == 8) {
                    grid.setCtrlState(0);
                }
            }
        } else {
            //蓝图模式
            ViewManager.ins.showtips("已切换蓝图模式");
            this.clicklist.touchable = false;
            for (let i of this.otherboardplaneList) {
                i.visible = true;
                i.alpha = 0.5;
                i.addClick();
            }
            for (let i = 0; i < this.clicklist.numItems; i++) {
                const grid = this.clicklist.getChildAt(i) as Grid;
                if (grid.state == 0) {
                    grid.setCtrlState(8);
                }
            }
        }
    }
    private clickSkillList(item: SkillItemRender): void {
        if (GameModels.game.Round <= 0) {
            ViewManager.ins.showtips(`游戏未开始`);
            return;
        }
        if (!GameModels.game.AckUid || GameModels.game.AckUid != GameModels.info.playerInfo.UserId) {
            ViewManager.ins.showtips(`不是我的回合，无法攻击`);
            return;
        }
        if (this.useSkill) {
            ViewManager.ins.showtips(`本回合已使用过道具`);
            return;
        }
        if (item.count <= 0) {
            ViewManager.ins.showtips(`${item.vo.cfg.name}数量不足`);
            return;
        }
        if (this.useSkillCount >= 5) {
            ViewManager.ins.showtips(`单局游戏最多使用五次道具`);
            return;
        }
        this.useSkillCount++;
        this.useSkill = true;
        item.setCountTxt(item.count - 1);
        switch (item.vo.cfg.id) {
            case 1002:
                //追踪导弹
                ViewManager.ins.showtips(`使用追踪导弹`);
                // this.useItem1002();
                this.useItem = 1002;
                GameModels.game.send_ReqUseItem(1002);
                // AudioManager.ins.playShot(`music/v6`);
                break;
            case 1003:
                //核弹
                ViewManager.ins.showtips(`使用核弹,请选择攻击位置`);
                this.useItem = 1003;
                break;
            case 1004:
                //干扰弹
                ViewManager.ins.showtips(`使用干扰弹,对方下回合无法攻击`);
                GameModels.game.send_ReqUseItem(1004);
                AudioManager.ins.playShot(`music/v7`);
                this.useItem = 1004;
                break;
            case 1005:
                //能量护盾
                ViewManager.ins.showtips(`使用护盾,下回合不会受到伤害`);
                this.ctrl_myhudun.selectedIndex = 1;
                GameModels.game.send_ReqUseItem(1005);
                this.useItem = 1005;
                break;
        }

    }
}